package cn.jayslong.weibo;

import java.io.IOException;
import java.net.NoRouteToHostException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class LoadPage
{
	public byte[] getPageCode(String url) throws SocketTimeoutException, SocketException
	{
		GetClient gc = new GetClient();
		HttpClient client = null;
		boolean run = true;
		int runCount = 0;
		while(run && runCount<3)
		{
			try
			{
				client = gc.getClient();
				run = false;
			} catch (NoRouteToHostException e1)
			{
				Log.log("网络连接错误..请检查网络连接.\n"+url,e1);
				runCount++;
				run = true;
			}
		}
		GetMethod getMethod = new GetMethod(url);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());

		
		run = true;
		runCount = 0;
		while(run && runCount<3)
		{
			try
			{
				client.executeMethod(getMethod);
				run = false;
				return getMethod.getResponseBody();
	
			} catch (java.net.NoRouteToHostException e)
			{
				Log.log("网络中断,请检查网络连接..\n"+url,e);
				runCount++;
				run = true;
			} catch (HttpException e)
			{
				Log.log("网络异常,请检查网络连接..\n"+url,e);
				runCount++;
				run = true;
			} catch (java.net.SocketTimeoutException e)
			{
	//			throw e;
				Log.log("网络连接超时,自动重试"+(runCount+1)+"次..\n"+url,e);
				runCount++;
				run = true;
				if (runCount>=6)
				{
					runCount=0;
					throw e;
				}
			} catch (SocketException e)
			{
				Log.log("网络连接被重置,自动重试"+(runCount+1)+"次..\n"+url,e);
				runCount++;
				run = true;
				if (runCount>=6)
				{
					runCount=0;
					throw e;
				}
			}
			catch (IOException e)
			{
				Log.log("网络读写异常,请检查网络连接..\n"+url,e);
				runCount++;
				run = true;
			} finally
			{
				getMethod.releaseConnection();
			}
		}		
		Log.log("下载页面失败!!!!!!!\n"+url);
		return null;
	}

//	public byte[] InputStreamToByte(InputStream iStrm) throws IOException
//	{
//		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
//		int ch;
//		while ((ch = iStrm.read()) != -1)
//		{
//			bytestream.write(ch);
//		}
//		byte imgdata[] = bytestream.toByteArray();
//		bytestream.close();
//		return imgdata;
//	}
}